package cn.geminis.crypto.core.util;

import cn.geminis.core.exception.CommonException;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.paddings.PKCS7Padding;

import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.UUID;

/**
 * @author Allen
 */
public class ByteUtils {

    private ByteUtils() {
    }

    public static byte[] pkcs7Padding(byte[] data, int length) {
        PKCS7Padding padding = new PKCS7Padding();
        int fullLength = (data.length / length + 1) * length;
        byte[] newData = Arrays.copyOf(data, fullLength);
        padding.addPadding(newData, data.length);
        return newData;
    }

    public static byte[] pkcs7UnPadding(byte[] data) {
        PKCS7Padding padding = new PKCS7Padding();
        int count = 0;
        try {
            count = padding.padCount(data);
        } catch (InvalidCipherTextException e) {
            throw new CommonException("PKCS7去填充错误", e);
        }
        return Arrays.copyOf(data, data.length - count);
    }

    public static byte[] fromUuid(UUID uuid) {
        var bb = ByteBuffer.wrap(new byte[16]);
        bb.putLong(uuid.getMostSignificantBits());
        bb.putLong(uuid.getLeastSignificantBits());
        return bb.array();
    }
}
